package com.bjsxt.base.mytest;

import java.util.HashMap;

public class FixedMultipleInstance {

    private FixedMultipleInstance() {

    }

    /**
     * 定义一个缺省的key值前缀
     */
    private static final String CACHE_KEY = "cacheKey";
    /**
     * 初始化数目
     */
    private static final int INITIAL_NUM = 1;
    /**
     * 用来记录正在使用第几个实例，到了控制的最大数目，就从初始化开始1
     */
    private static int num = INITIAL_NUM;
    /**
     * 定义控制实例的最大数目
     */
    private static final int MAX_NUM = 3;
    /**
     * 缓存实例容器
     */
    private static HashMap<String, FixedMultipleInstance> cachedMap = new HashMap<>();

    public static FixedMultipleInstance getFixedMultipleInstance() {
        String key = CACHE_KEY + num;
        FixedMultipleInstance fixedMultipleInstance = cachedMap.get(key);
        if (fixedMultipleInstance == null) {
            fixedMultipleInstance = new FixedMultipleInstance();
            cachedMap.put(key, fixedMultipleInstance);
        }
        //把当前的实例的序号加一
        num++;
        if (num > MAX_NUM) {
            // 如果实例的序号已经达到最大数目了，那就重复从1开始获取
            num = INITIAL_NUM;
        }
        return fixedMultipleInstance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            int hashCode = FixedMultipleInstance.getFixedMultipleInstance().hashCode();
            System.out.println(hashCode);
        }
    }
}
